<template>
	
	<view id="app" style="padding-top:0rem;background-color: #F5F5F5;z-index: 9999999;" @touchmove.stop.prevent="clear">
	  <!-- 头部 -->
	 
	  <!-- 页面的主要内容 -->
		<view class="wrap wrap-sku" style="padding:25rpx;max-height:85vh;overscroll-behavior:none;">
			<view class="product-box">
				<!-- 图片显示区 -->
        <view class="item_img">
          <view style="display: flex;">
						<view class="item_img_image">
							<image v-if="props.selectObj.product_image" :src="props.selectObj.product_image" mode=""></image>
							<image v-else src="../../static/images/my/noPictures.png" mode=""></image>
						</view>
						<view style="margin-left:20rpx;" v-if="props.selectObj.product_id">
              <nut-price :price="props.selectObj.product_price" :decimal-digits="2" :thousands="false"/>
							<view style="display: flex;margin-top:10rpx;">
								<view class="tip">支持7天无理由退货</view>
								<view class="tip">30天价保</view>
							</view>
						</view>
            <view v-else>
              <view style="display: flex;margin-top:10rpx;">
                <view>套餐详情</view>

              </view>
            </view>
					</view>

<!--          &lt;!&ndash;地址选择区&ndash;&gt;-->
<!--					<view class="item_text" v-if="state.showAddress">-->
<!--						<view style="font-size: 30rpx;font-weight: bold;">{{addressList[addressIndex].name}} {{addressList[addressIndex].phone}} {{addressList[addressIndex].area}}</view>-->
<!--						<view style="font-size: 26rpx;margin-top:20rpx;">{{addressList[addressIndex].delivery}} {{addressList[addressIndex].date}}-->
<!--							<text style="color:#E3391F;font-weight: bold;">[{{addressList[addressIndex].week}}]</text>-->
<!--						</view>-->
<!--					</view>-->

          套餐包含产品详情
          <view class="item_text" v-if="props.selectObj.product_id" style="margin-top:10px;border-radius:10px;background-color: #fff;">
            <view class="info_title" style="font-size: 30rpx;font-weight: bold;">
              {{ props.selectObj.product_code }} {{ props.selectObj.product_name }}
            </view>
            <view class="info_lat" v-if="props.selectObj.diy_name" style="color:#E3391F;font-weight: bold;">
              已选： {{ props.selectObj.diy_name }}
            </view>
            <view class="info_code" style="font-size: 26rpx;margin-top:20rpx;">
              <text>存货编码： {{ props.selectObj.product_id }} </text>
              <text style="padding-left: 20rpx;">装箱规格:{{ props.selectObj.zxgg }}</text>
              <text style="padding-left: 20rpx;">起订量: {{
                  props.selectObj.qdl === 0 ? '不限量' : props.selectObj.qdl
                }}
              </text>
            </view>
          </view>
        </view>

				
				<!-- 规格选择区 -->
				<scroll-view scroll-y="true"  v-if="props.skuData.combo.length>0" style="margin-top:10px;border-radius:10px;overflow-y: auto;flex: 1; background-color: #fff;padding:5rpx 2rpx;max-height: 35vh">
					<view v-for="(combo,n) in props.skuData.combo" :key="n" >
            <view class="comboList">
              <image :src="combo.product_image"></image>
              <view class="combo_info">
                <view class="combo_name">{{combo.spmc}}</view>
                <view class="combo_code">{{combo.psid}}</view>
                <view class="combo_zxgg">{{combo.xhgg}}</view>
                <view class="combo_price">¥{{combo.je}}</view>
              </view>
              <view class="combo_pcs_dj">{{combo.ass_num}}/{{combo.jldw}}</view>
            </view>

          </view>

				</scroll-view>
				<view class="product-footer" style="z-index: 9999">
					<view style="display: flex;align-items: center;justify-content: space-between;">
						<view style="font-size:24rpx;color:#E3391F;">合计：
							<nut-price :price="totalAmount" :decimal-digits="2" :thousands="false"/>
						</view>
						<view style="display: flex;align-items: center;font-weight: bold;">
							<view style="font-size: 28rpx;color:#DB3922;margin-right:30rpx;font-weight: normal;" v-if="props.selectObj.qdl>1">
								({{props.selectObj.qdl}}件起订)
							</view>
							<nut-input-number  :step='1' :min="props.selectObj.qdl" v-model="buyNumber" button-size="30"
																 input-width="50" @change="numberInput"/>
						</view>
					</view>
					<view style="margin-top: 5px">
						<nut-button  block :type="props.buttonStyle.type" :disabled="props.buttonStyle.disabled" @click="addCartList">{{props.buttonStyle.name}}</nut-button>
					</view>

					<!--			<view  class="rightPay"></view>-->
				</view>
			</view>
		</view>
	  <!-- 页面结束 -->
	</view>

</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
import {addCart} from "../../api/api";
import price from "../../uni_modules/sky-nutui/components/sky-nutui/packages/__VUE/price/index.vue";
	const emit = defineEmits(['getSelectedSku','closeTcSku'])


	const props = defineProps({
    addressList: {
      type: Object,
      default: [
        {
          name:'张三',
          phone:'13803116601',
          area:'河北省石家庄市裕华区裕翔街道',
          delivery:'京东快递',
          date:'9月23日',
          week:'周一',
        },
        {
          name:'李四',
          phone:'13803116602',
          area:'河北省石家庄市元氏县常山路',
          delivery:'京东快递',
          date:'9月24日',
          week:'周二',
        },
      ]
    },
    skuData:{ //规格
      type: Object,
      default: {
        spec: [],//规格列表
        fit_products: [],//赠送的产品
        products: [] ,//规格对应的商品列表,
        combo:[]//套餐列表
      }
    },
    selectObj: {//选中的商品信息
      type: Object,
      default: {product_price:0,qdl:1}
    },
    buttonStyle:{
      type: Object,
      default: {
        name: "立即购买",
        type: "primary",
        disabled:true
      }
    }
	})
	const addressIndex = ref(0)

  //const data=ref({})
  const state=ref({
        selectArr: [], //存放被选中的值
        subIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
        price: "", //选中规格的价钱
        showAddress:false,//是否显示地址
      }
  )
	const buyNumber = ref(1)
  const door_height = ref(props.selectObj?.door_height_options?.[0] ?? '')
  const door_width = ref(props.selectObj?.door_width_options?.[0] ?? '')
  const door_thickness = ref('')
	const array=	ref(['中国', '美国', '巴西', '日本'])
	const index = ref(0)
	const index2 = ref(0)

	onMounted(() => {
	  console.log('onMounted执行。。。' ,props.skuData.combo);
	  setDefaultOption();
	});

  const totalAmount=computed(()=>{
		let a, b = (Number(door_height?.value) && Number(door_width?.value)) ? (parseFloat(door_height?.value) * parseFloat(door_width?.value)) / 1000000 : 1;
		if (props.skuData.spec.length > 0) {
			a = parseFloat(props.selectObj.product_price) * parseFloat(buyNumber?.value) * b;
			console.log("b=" + b);
		} else {
			a = parseFloat(props.selectObj.product_price) * parseFloat(buyNumber?.value);
		}
    if(a<=0){
      props.buttonStyle.disabled=true;
    }else{
      props.buttonStyle.disabled=false;
    }
    //console.log("单价="+state.value.selectObj.product_price+"数量="+buyNumber.value);
    return a;
  })

	const bindPickerChangeHeight=(e)=> {
	index.value = e.detail.value
	door_height.value=props.selectObj.door_height_options[index.value]
	}
	const bindPickerChangeWidth=(e)=> {
	index2.value = e.detail.value
	door_width.value=props.selectObj.door_width_options[index2.value]
	}
	const numberInput=(val,event)=>{

    console.log('数量变化：'+val)
	}

  const specificationBtn=(item, n, index)=>{
   // console.log("state.value.selectArr="+JSON.stringify(state.value.selectArr)+"n="+n+" index="+index);
    if (state.value.selectArr[n] != item) {
      state.value.selectArr[n] = item; //当前规格选中,赋值为选项的名字(蓝色、黑色)
      state.value.subIndex[n] = index; //设置此项为选中
    } else {
      state.value.selectArr[n] = "";
      state.value.subIndex[n] = -1; //去掉选中的颜色
    }
    checkItem()

  }
	


  //设置默认选项
  const setDefaultOption=()=>{
    //设置默认选项
    if(props.selectObj.diy_name){
      let option = props.skuData.spec;
      let result = []; //定义数组储存被选中的值
      for (let i in option) {
        result[i] = state.value.selectArr[i] ? state.value.selectArr[i] : "";
      }
      let isNullOpt=true;
      for(let i in result){
        if(result[i] != ""){
          isNullOpt=false;
          break;
        }
      }
      if(isNullOpt){
        console.log("设置默认选项"+props.selectObj.diy_name);
        result=props.selectObj.diy_name.split(",");
        for (let i in option) {
          for (let k in option[i].options) {
            if(option[i].options[k].title == result[i]){
              state.value.selectArr[i] = result[i];
              state.value.subIndex[i]=k;
              break;
            }
          }
        }
      }
    }

  }

const addCartList = () => {
  let session = uni.getStorageSync('session');
  // 获取宽度
  let param = {
    // 接口
    proname: 'INTC01',
    action: 'call',
    // 门店编码
    opr_man: session.DWDM,
    // 存货编码
    code: props.selectObj.product_id,
    // 单价
    product_price: props.selectObj.product_price,
    // 长度
    Product_MJ: door_height.value,
    product_height: door_height.value,
    // 宽度
    Product_Width: door_width.value,
    product_width: door_width.value,
    // 厚度
    product_thickness: door_thickness.value,
    // 数量
    back_num: buyNumber.value,
    //  备注
    // Product_Memo:this.bz,
    // 订单编号
    back_code: 'XS' + session.DWDM,
    // 多规格 - 定制属性
    attribute: props.selectObj.diy_name,
    // 定制属性
    diy_value: props.selectObj.sku_value,
    // 排序号
    d_PXH: '',
    // 启用折扣
    QYZK: '10',
  }
  if (props.skuData.back_code){
    param.back_code = props.skuData.back_code
  }
  console.log("props.skuData.back_code",props.skuData.back_code)
  console.log("加入购物车请求报文", param)
  addCart(param).then((res => {
    console.log("加入购物车响应报文", res)
    if (res.result == 'ok') {
      uni.showToast({
        title: '加入成功！',
        icon: 'none'
      })
      //state.value.showBasic = false
      //show_one_sku.value = false
      emit('closeTcSku', 'addCart');
    }
  }))
}

//加入本地缓存的购物车
const addStorageCart = () => {
  let session = uni.getStorageSync('session');
  //一个产品信息
  let record = {
    // 门店编码
    Agent_Code: session.DWDM,
    // 存货编码
    Product_Code: props.selectObj.product_id,
    // 单价
    product_price: props.selectObj.product_price,
    // 长度
    Product_MJ: '',
    product_height: '',
    // 宽度
    Product_Width: '',
    product_width: '',
    // 厚度
    product_thickness: '',
    // 数量
    Product_Num: buyNumber.value,
    //小计
    back_amount:totalAmount.value,
    //  备注
    // Product_Memo:this.bz,
    // 订单编号
    Back_Code: 'XS' + session.DWDM,
    // 多规格 - 定制属性
    attribute: props.selectObj.diy_name,
    // 定制属性
    diy_value: props.selectObj.sku_value,
    // 启用折扣
    QYZK: '10',
  }
  console.log("加入缓存购物车请求报文", record)
  let shopCart=uni.getStorageSync("shopCart");
  console.log("本地缓存的购物车:"+JSON.stringify(shopCart));
  if(shopCart == ""){
    let newShopCart=[];
    newShopCart.push(record);
    uni.setStorageSync("shopCart",newShopCart);
  }else{
    console.log("存在吗？",shopCart.includes(record))
    if(!shopCart.includes(record)) {
      shopCart.push(record);
      uni.setStorageSync("shopCart",shopCart);
    }

  }
  shopCart=uni.getStorageSync("shopCart");
  console.log("添加产品后缓存的购物车",shopCart);

}


	const clear = ()=>{
		
	}

</script>


<style scoped lang="scss">
	.title{
		font-size:30rpx;
		font-weight: bold;
		margin:10rpx;
	}
	.item{
		font-size:28rpx;
		padding:20rpx 40rpx;
		color: #383838;
		background-color: #F2F2F2;
		border-radius: 15rpx;
		display: inline-block;
		margin:10rpx 10rpx;
	}
	.productActive{
		color: #D53D42;
		background-color: #FCEDEA;
		border: 1rpx solid #D53D42;
	}
  .noneActive{
    opacity: 0.5;
    color: #777;
    text-decoration: line-through;
    background-color: #F2F2F2;
  }
	.item_img_image image{
		width:80px;
		height:80px;
		border-radius: 10px;
	}
	.tip{
		color:#E3391F;
		border:1rpx solid #E3391F;
		border-radius: 5rpx;
		font-size: 20rpx;
		margin-right:10rpx;
	}
	.item_text{
		padding:20rpx;
	}
	.code{
		color:#8B8B8B;
		font-size: 24rpx;
		margin-left:20rpx;
	}
  .sku_spec_memo{
    font-size: 28rpx;
    color:#DB3922;
    margin-right:30rpx;
    font-weight: normal;
  }
	.rightPay{
		color:#FEFBFA;
		background-color: #F43A45;
		text-align: center;
		border-radius: 40rpx;
		padding:20rpx 0;
		font-weight: bold;
		margin-top:10rpx;
	}
	.product-footer{
		background-color: #fff;
		padding:20rpx;
		padding-bottom: 0;
		margin-top: auto; /* 这会将 .product-footer1 推到底部 */
		bottom:22px;
		width:94%;
	}
	.numberInput{
		background-color: #F2F2F2;
		font-size:30rpx;
		width:60px;
		height:35px;
		color:black;
		font-weight: bold;
		margin:0 15rpx;
		text-align: center;
	}
	.bordered-input {
		//margin-top: 5px;
		width: 100px;
		height: 35px;
		border: 2px solid #ccc; /* 设置边框为2像素宽，颜色为浅灰色 */
		border-radius: 4px; /* 可选：设置边框圆角 */
		box-sizing: border-box; /* 确保内边距和边框被包含在元素的总宽度和高度内 */
	}
  .comboList {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #e0e0e0; /* 分割线 */
  }
  .combo_info{
    width: 50%;
  }

  .comboList image {
    width: 80px; /* 图片宽度 */
    height:80px; /* 图片高度 */
    margin-right: 10px; /* 图片与文本之间的间距 */
  }

  .combo_name, .combo_code, .combo_zxgg, .combo_price, .combo_pcs_dj {
    margin: 5px 0; /* 每个信息之间的间距 */
    font-size: 10px;
  }

  .combo_price {
    color: red; /* 价格颜色 */
    font-weight: bold; /* 价格字体加粗 */
  }

  .combo_pcs_dj {
    margin-left: auto; /* 将数量和单价推到最右边 */
  }
</style>